<template>
  <div class="product-detail-container">
    <el-skeleton :rows="5" animated v-if="loading" />
    <!-- 商品详情内容 -->
    <el-card shadow="never" class="product-card" v-else>
      <el-row :gutter="40">
        <el-col :span="12">
          <div class="product-image">
            <el-image 
              :src="productDetail.mainImage" 
              fit="contain" 
              class="main-image"
              :preview-src-list="[productDetail.mainImage]" 
            />
          </div>
        </el-col>

        <el-col :span="12">
          <div class="product-info">
            <h1 class="product-title">{{ productDetail.name }}</h1>

            <!-- 商品描述 -->
            <div class="product-description" v-if="productDetail.description">
              <h3 class="description-title">商品介绍</h3>
              <p class="description-content">{{ productDetail.description }}</p>
            </div>

            <div class="info-group">
              <div class="info-item">
                <span class="info-label">品牌：</span>
                <span class="info-value">{{ productDetail.brand || '暂无品牌信息' }}</span>
              </div>
              
              <div class="info-item">
                <span class="info-label">价格：</span>
                <span class="info-value price">¥{{ productDetail.price.toFixed(2) }}</span>
              </div>
              
              <div class="info-item">
                <span class="info-label">库存：</span>
                <span class="info-value stock">
                  {{ productDetail.stock }}件
                  <span v-if="productDetail.stock < 10 && productDetail.stock > 0" class="stock-tip">(库存紧张)</span>
                  <span v-if="productDetail.stock <= 0" class="out-of-stock">(已售罄)</span>
                </span>
              </div>

              <div class="info-item quantity-item" v-if="productDetail.stock > 0">
                <span class="info-label">数量：</span>
                <el-input-number 
                  v-model="quantity" 
                  :min="1" 
                  :max="productDetail.stock" 
                  size="small"
                  @change="updateStockDisplay"
                />
              </div>
            </div>

            <div class="action-buttons">
              <el-button 
                type="primary" 
                size="large" 
                @click="addToCart"
                :loading="addingToCart"
                :disabled="productDetail.stock <= 0"
              >
                <el-icon><ShoppingCart /></el-icon>
                加入购物车
              </el-button>
              <el-button 
                type="danger" 
                size="large"
                @click="buyNow"
                :disabled="productDetail.stock <= 0"
              >
                立即购买
              </el-button>
            </div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<script setup>

import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ShoppingCart } from '@element-plus/icons-vue'
import { ElMessage, ElSkeleton } from 'element-plus'
import { getProductDetail } from '@/api/product'
import { addToCart as apiAddToCart } from '@/api/cart'

const route = useRoute()
const router = useRouter()

const productDetail = ref({
  id: 0,
  name: '加载中...',
  brand: '',
  price: 0,
  stock: 1,
  description: '',
  mainImage: 'https://via.placeholder.com/400',
  images: [],
  originalStock: 0
})

const quantity = ref(1)
const loading = ref(true)
const addingToCart = ref(false)


const updateStockDisplay = () => {
  productDetail.value.stock =  Math.max(
    0, 
    productDetail.value.originalStock - quantity.value + 1 
  )
}

// 获取商品详情
const fetchProductDetail = async () => {
  try {
    loading.value = true
    const res = await getProductDetail(route.params.id)
    
    if (res.code === 0 && res.data) {
      productDetail.value = {
        ...res.data,
        mainImage: res.data.mainImage 
          ? `${res.data.mainImage}`
          : 'https://via.placeholder.com/400',
        originalStock: res.data.stock,
        stock: res.data.stock
      }
      quantity.value = 1
    }
  } catch (error) {
    ElMessage.error('获取商品详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

const addToCart = async () => {
  try {
    addingToCart.value = true;
    const res = await apiAddToCart({
      productId: productDetail.value.id,
      quantity: quantity.value
    });
    
    if (res.code === 0) {
      ElMessage.success('已加入购物车');
      // 更新库存显示
      productDetail.value.originalStock -= quantity.value;
      updateStockDisplay();
      router.push('/cart');
    } else {
      ElMessage.error(res.message || '加入购物车失败');
    }
  } catch (error) {
    if (error.response?.status === 401) {
      ElMessage.warning('请先登录');
      router.push('/login?redirect=' + encodeURIComponent(route.fullPath));
    } else {
      ElMessage.error(error.response?.data?.message || '操作失败');
    }
  } finally {
    addingToCart.value = false;
  }
};
// 立即购买
const buyNow = () => {
  router.push({
    path: '/order/confirm',
    query: {
      productId: productDetail.value.id,
      quantity: quantity.value
    }
  })
}

onMounted(fetchProductDetail)
</script>

<style>
.product-detail-container {
  padding: 20px;
  min-height: 500px;
  background-color: #fff;
}

.product-card {
  border-radius: 8px;
  background-color: #fff;
  border: none;
}

/* 主图容器样式 - 移除灰色背景，添加淡入动画 */
.main-image {
  width: 100%;
  height: 400px;
  border-radius: 4px;
  position: relative;
  overflow: hidden;
}

.main-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0;
  animation: fadeIn 0.5s ease-in forwards;
}

/* 缩略图列表样式 - 移除灰色背景 */
.thumbnail-list {
  display: flex;
  margin-top: 10px;
  flex-wrap: wrap;
  gap: 10px;
}

.thumbnail {
  width: 60px;
  height: 60px;
  cursor: pointer;
  border-radius: 4px;
  overflow: hidden;
  transition: all 0.3s;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0;
  animation: fadeIn 0.5s ease-in forwards;
}

.thumbnail:hover {
  transform: scale(1.05);
}

/* 淡入动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.product-title {
  font-size: 24px;
  margin-bottom: 20px;
  color: #333;
  font-weight: 500;
}

.description-title {
  font-size: 18px;
  color: #333;
  margin-bottom: 10px;
  font-weight: 500;
}

.description-content {
  color: #666;
  line-height: 1.8;
  margin-bottom: 20px;
  font-size: 15px;
}

.info-group {
  margin: 25px 0;
  padding: 0;
}

.info-item {
  margin-bottom: 15px;
  font-size: 16px;
  display: flex;
  align-items: center;
}

.info-label {
  color: #666;
  width: 80px;
  font-size: 16px;
}

.info-value {
  flex: 1;
  font-size: 16px;
  color: #333;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.stock {
  color: #333;
}

.stock-tip {
  color: #e6a23c;
  margin-left: 5px;
}

.out-of-stock {
  color: #f56c6c;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  gap: 15px;
}

.action-buttons button {
  flex: 1;
  height: 48px;
  font-size: 16px;
}

.quantity-item {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #f0f0f0;
}
</style>